#!/usr/local/bin/python
# -*- coding: utf-8 -*-

'''
    道具处理
'''

import logging, traceback
from tornado.escape import json_encode,json_decode
import log

import util
from util import ConfigManager
import const
import mysqlHelper

import user
from user import UserManager

import bar_order
from bar_order import Room, BarOrderManager
import code_define
from store import *
from props_manager import *
import task

logger = logging.getLogger(__name__)


def _createPropsUsingBody(data, tmpOwnerUser, tmpTargetUser, type3, tmpGoodsID, tmpRecID, tmpBeginTime, tmpEndTime):
    '''构建正在使用的道具的个体信息'''
    ownerUID = tmpOwnerUser.getUID()
    ownerNickname = tmpOwnerUser.getNickname()

    tmpIntervalTime = tmpEndTime - tmpBeginTime     #道具的可使用时长(秒)
    tmpBeginTime = time.time()                      #道具开始使用时间
    tmpEndTime = tmpBeginTime + tmpIntervalTime     #道具结束使用时间
    
    #---从"正在使用的道具"列表,删除相同的道具，插入新道具    
    tmpNewGoodsObj = {}
    tmpNewGoodsObj["uid"] = tmpTargetUser.getUID()                 #对某人使用(目标用户)
    tmpNewGoodsObj["nickname"] = tmpTargetUser.getNickname()       #目标用户昵称
    tmpNewGoodsObj["goods_id"] = tmpGoodsID                        #道具ID
    tmpNewGoodsObj["rec_id"] = tmpRecID                            #道具记录ID(酒吧类道具记录ID为0)
    tmpNewGoodsObj["buy_time"] = tmpBeginTime           #使用开始时间(秒)
    tmpNewGoodsObj["limit_time"] = tmpEndTime           #使用结束时间(秒)
    tmpNewGoodsObj["interval_time"] = tmpIntervalTime   #可使用时长(秒)    
    tmpNewGoodsObj["use_state"] = int(tmpTargetUser.isMyPropsUsing(type3)) #0:表示默认, 1:表示替换上一个同样的道具 
    if type3 in ['horn']:#大喇叭;
        data_dict = json_decode(data)
        #判断性别
        if tmpOwnerUser.getSex()==0: #性别：女
            sexChar = "♀"
            sexColor = "FF00E4"
        else:
            sexChar = "♂"
            sexColor = "337FE5"
        sexCharColor = '<font color="%s">%s</font>'%(sexColor, sexChar)      #给性别加颜色
        ownerNicknameColor = '<font color="#FFFF00"><u>%s</u></font>'%(ownerNickname)      #给昵称加颜色
        tmpNewGoodsObj['content'] = sexCharColor + ownerNicknameColor + '<font color="#ff8800">:%s</font>'%(data_dict.get('content'))    #大喇叭消息内容
        #print "@wudi@>process_props>", tmpNewGoodsObj['content']
    
    tmpUsingPropsUser = {"uid":ownerUID, "nickname": ownerNickname}#施法者信息
    tmpNewUsingObj = {}
    tmpNewUsingObj["props"] = tmpNewGoodsObj
    tmpNewUsingObj["user"] = tmpUsingPropsUser
    
    return tmpNewGoodsObj, tmpUsingPropsUser, tmpNewUsingObj


def _inserMyBodyInfoPropsToMyUsingProps(tmpUser, type3, infoObj):
    if infoObj:    
        tmpGoodsID = infoObj.get("id")
        tmpRecID = infoObj.get("rec_id")
        tmpBeginTime = infoObj.get("buy_time")  
        tmpEndTime = infoObj.get("limit_time")   #装饰类道具的结束时间 是按购买时候开始计算                         

        if time.time() > tmpEndTime:
            log.print_warning(logger, "_inserMyBodyInfoPropsToMyUsingProps exec, props outtime, uid[%s], type3[%s], tmpGoodsID[%s]" 
                              % (tmpUser.getUID(), type3, tmpGoodsID))
            return
        
        tmpBodyTuple = _createPropsUsingBody(None, tmpUser, tmpUser, type3, tmpGoodsID, tmpRecID, tmpBeginTime, tmpEndTime)
        tmpNewUsingObj = tmpBodyTuple[2]
        #---"正在使用的道具"删除相同的道具，插入新道具 
        tmpUser.delAndInsertMyUsingProps(type3, tmpNewUsingObj) 
    

#---穿戴装饰类道具(用户穿戴接口调用)
def usePropsAttire(tmpUser):
    if tmpUser is None:
        return

#    'sinensis'      #'大红花'          #'装饰类, 人缘+，每次移植(穿戴)须付费, (过期不续费, 隐藏超出人缘数的好友)'); 
#    'halo'          #'光环'            #'装饰类, 跟我聊天的人，可得额外经验、金币、魅力加成'); 
#    'cheeky'        #'厚脸皮'          #'装饰类, 插足后防止提前被踢'); 
#    'stealth'       #'隐形符'          #'装饰类, 防止被插足'); 

    bEdit = False  #是否有修改

    #把“我正在使用”的装饰类道具删除 
    tmpMyUsingProps = tmpUser.getMyUsingProps()#我正在使用的道具
    if not isinstance(tmpMyUsingProps, dict):
        return
    for type3, propsInfo in tmpMyUsingProps.items():
        if type3 in ("sinensis", "halo", "cheeky", "stealth"):
            bEdit = True
            tmpMyUsingProps.pop(type3)
   
    #插入我的穿戴信息里所有的非过期的装饰类道具到“我正在使用”的道具里
    from props_manager import *
    
    tmpMyBodyInfo = tmpUser.getMyBodyInfo()
    if tmpMyBodyInfo:
        tmpGoodsList = tmpMyBodyInfo.get("goods")
        if tmpGoodsList:
            for itemDict in tmpGoodsList: 
                tmpGoodsID = itemDict.get("id")
                if tmpGoodsID and tmpGoodsID > 0:
                    tmpPropsInfo = PropManager.instance().getOneMyPropsExt(tmpUser, tmpGoodsID) #获取我购买的道具信息
                    if tmpPropsInfo:
                        type3 = tmpPropsInfo.get("type_3") 
                        _inserMyBodyInfoPropsToMyUsingProps(tmpUser, type3, tmpPropsInfo)
                        bEdit = True
                        
    #---更新目标用户"正在使用的道具"到DB
    if bEdit:
        PropManager.instance().updateUsingPropsToDB(tmpUser)

#---购买道具(用户购买接口调用)
def buyPropsExt(cmd, tmpSendMsgUtil, tmpUser, tmpGoodsList):
    if tmpUser:
        for tmpItem in tmpGoodsList: 
            goods_id = tmpItem.get('id')
            if not goods_id:
                continue
            
            goods_info = store.get_goods_info(goods_id) 
            if not goods_info:
                continue
            type1 = goods_info.get('type_1')
            if not type1 or type1 not in ['props']:
                continue
        
            type3 = goods_info.get('type_3')
            if not type3:
                continue
            if type3 in ["brooch"]:  #胸花(酒吧大厅T台票) 只能同时购买使用一个胸花
                if PropManager.instance().isUsingPropBrooch(tmpUser):
                    tmpSendMsgUtil.update_res("useing_same_props_brooch")
                    tmpSendMsgUtil.send(cmd)
                    return False
    return True

    
#---"插入正在使用的道具列表", 更新DB, 构建道具回应消息
def _create_props_msg(data, tmpOwnerUser, tmpTargetUser, type3, tmpGoodsID, tmpRecID, tmpBeginTime, tmpEndTime, tmpSendMsgUtil):
    ownerUID = tmpOwnerUser.getUID()
    ownerNickname = tmpOwnerUser.getNickname() 
    
    tmpBodyTuple = _createPropsUsingBody(data, tmpOwnerUser, tmpTargetUser, type3, tmpGoodsID, tmpRecID, tmpBeginTime, tmpEndTime)
    tmpNewGoodsObj = tmpBodyTuple[0]
    tmpUsingPropsUser = tmpBodyTuple[1] 
    tmpNewUsingObj = tmpBodyTuple[2]

    #大喇叭,酒水,果盘,金币卡, 人缘卡,(胸花), 深水炸弹, 防打搅牌 , 等级礼包  等道具 不需要插入"正在使用的道具"
    tmpListNotSaveProps = ['horn', 'wine', 'compote', 'goldcar', 'energycard', 'brooch', 'bomb', 'nobother', 'levelgift']
    if type3 not in tmpListNotSaveProps:  
        tmpTargetUser.delAndInsertMyUsingProps(type3, tmpNewUsingObj)   #---"正在使用的道具"删除相同的道具，插入新道具      
        PropManager.instance().updateUsingPropsToDB(tmpTargetUser)      #---更新目标用户"正在使用的道具"到DB
    
    #---消息内容
    tmpSendMsgUtil.update_item("user", tmpUsingPropsUser)
    tmpSendMsgUtil.update_item("props", tmpNewGoodsObj)
    
        
#---背包类道具处理
def _use_props_pack(cmd, request, data, tmpOwnerUser, tmpTargetUser, bUseToOther, tmpGoodsObj, tmpGoodsID, tmpRecID):
    type1 = tmpGoodsObj.get("type_1")
    type2 = tmpGoodsObj.get("type_2")
    type3 = tmpGoodsObj.get("type_3")

    socket_id = request.socket_id
    ownerUID = tmpOwnerUser.getUID()
    targetUID = tmpTargetUser.getUID()
    
    log.print_debug(logger, "_use_props_pack exec, sockID:[%s], owner:[%s] to target:[%s] using props:[%s], goods_id[%s]" 
                      % (socket_id, ownerUID, targetUID, type3, tmpGoodsID))
    
    tmpBarManager = BarOrderManager.instance()      #酒吧名人堂管理对象    
    tmpSendMsgUtil = util.SendMsgUtil(request)      #消息发送器
    
    tmpSendMsgUtil.add_item("uid", ownerUID)        #使用者ID
    tmpSendMsgUtil.add_item("goods_id", tmpGoodsID) #道具ID
    tmpSendMsgUtil.add_item("type_3", type3)        #道具类别3
    
    #查看"我的道具列表" 是否存在 此道具, 
    tmpMyGoodsObj = PropManager.instance().getOneMyProps(tmpOwnerUser, type2, type3, tmpGoodsID)
    if tmpMyGoodsObj is None: #不存在则发错误消息， 退出
        tmpSendMsgUtil.update_res("not_my_props")  
        tmpSendMsgUtil.send(cmd)
        return
        
    if type3 in ['wine', 'compote', 'goldcar', 'energycard', 'levelgift']:
        tmpLogicMapObj = ConfigManager.getLogicInfo("default_logic") #获取默认配置项
        if type3 in ['wine']: #(酒水) '背包类, 勇气+');
            tmpVal = tmpGoodsObj.get('courage')
            ConfigManager.setLogicInfoVal_Courage(tmpLogicMapObj, tmpVal)
        elif type3 in ['compote']: #(果盘) '背包类, 人品+');
            tmpVal = tmpGoodsObj.get('quality')
            ConfigManager.setLogicInfoVal_Quality(tmpLogicMapObj, tmpVal)
        elif type3 in ['goldcar']: #(金币卡) '背包类, 金币+');     
            tmpVal = tmpGoodsObj.get('assets')
            ConfigManager.setLogicInfoVal_Gold(tmpLogicMapObj, tmpVal)
        elif type3 in ['energycard']: #人缘卡   (人缘+');     
            tmpVal = tmpGoodsObj.get('energy')
            ConfigManager.setLogicInfoVal_Energy(tmpLogicMapObj, tmpVal)

        elif type3 in ['levelgift']: #等级礼包   (加商品, 金币等');  
            if const.Config_props_levelgift_debug_open_random == 0:  # 1:开启几率; 0:不开启几率
                if tmpOwnerUser.getLevel() < tmpMyGoodsObj.get("level"): #使用 有等级限制
                    tmpSendMsgUtil.update_res("use_props_need_enough_level")  
                    tmpSendMsgUtil.send(cmd)
                    return
       
            tmpList = util.jsonDecodeToList(tmpGoodsObj.get('gift_goods_list'))  #格式如 [goods_id, {"gold":100}, {"exp":1}, , goods_id]
            tmpGoodsList = []
            tmpXX = ["gold","money","exp","courage","quality","energy","charm"]
            for tmpItem in tmpList:
                if isinstance(tmpItem, dict):
                    for key, val in tmpItem.items():
                        if key in tmpXX:
                            ConfigManager.setLogicInfoVal(tmpLogicMapObj, key, val)
#                    for tmpCol in ["gold","money","exp","courage","quality","energy","charm"]:
#                        tmpAdd = tmpItem.get(tmpCol, 0)
#                        ConfigManager.setLogicInfoVal(tmpLogicMapObj, tmpCol, tmpAdd)
                elif isinstance(tmpItem, int): #商品ID
                    tmpGoodsList.append(tmpItem)
            ConfigManager.setLogicInfoVal_gift_goods_list(tmpLogicMapObj, tmpGoodsList)
     
        #-修改并通知数值的变化--
        util.CountUserUtil.judgeAndEditExt(cmd, request, tmpOwnerUser.getUID(), tmpLogicMapObj, False)
     
    if type3 in ['brooch']:#---(胸花) '背包类, 酒吧大厅T台票')#插入T台队列     
        tmpBarManager.insertTUserList(tmpTargetUser) 
    elif type3 in ['king']:#---(后冠) '背包类, 独霸名人堂页面');#插入后冠队列 
        tmpBarManager.insertKingList(tmpTargetUser)    

    #'loupe'         #'放大镜'  #'背包类, 搭讪前可查看对方照片')
    #'photoscope'    #'透视镜'  #'背包类, 显示对方虚拟形象时，是裸体的')

    tmpRoom = None
    #---(泡泡) '背包类, 聊天泡泡' 需通知房间所有人 
    if type3 in ['popo']:
        room_id = tmpTargetUser.getRoomID(); #房间ID
        tmpRoom = tmpBarManager.getRoomExt(cmd, tmpSendMsgUtil, socket_id, room_id)
        if tmpRoom is None:     #当前房间不存在， 则发错误消息
            return
           
    #背包类, 从"我的道具列表"减少一个, 并更新DB
    PropManager.instance().decreaseMyPropsAndUpdateToDB(tmpOwnerUser, type2, type3, tmpGoodsID)
     
    #--- "插入正在使用的道具列表", 更新DB, 构建道具回应消息
    tmpRecID = tmpMyGoodsObj.get("rec_id")          #道具记录ID(酒吧类道具记录ID为0)
    tmpBeginTime = tmpMyGoodsObj.get("buy_time")    #道具购买时间
    tmpEndTime = tmpMyGoodsObj.get("limit_time")    #道具相对购买时间是结束时间
    _create_props_msg(data, tmpOwnerUser, tmpTargetUser, type3, tmpGoodsID, tmpRecID, tmpBeginTime, tmpEndTime, tmpSendMsgUtil)
        
    if type3 in ['horn']:#大喇叭, 所有人能看到我的发言或告白内容')(不需要放"正使用"列表)  
        tmpMsg = tmpSendMsgUtil.getEncodeContent()  #消息编码
        UserManager.sendMsgToAll(cmd, msg=tmpMsg)   #给系统所有人发消息
        return

    if type3 in ['popo']: #(泡泡) '背包类, 
        if tmpRoom:
            tmpRoom.sendMsgToAll(cmd, tmpSendMsgUtil)#给房间所有人发消息通知
            return

    #发送消息到目标者---
    tmpMsg = tmpSendMsgUtil.getEncodeContent()
    tmpSendMsgUtil.send(cmd, request=tmpTargetUser.getRequest(), msg=tmpMsg)


    
#---酒吧类道具处理(使用)--
def _use_props_bar_EXT(cmd, request, data, tmpOwnerUser, tmpTargetUser, bUseToOther, tmpGoodsObj, tmpGoodsID, tmpRecID):
    type1 = tmpGoodsObj.get("type_1")
    type2 = tmpGoodsObj.get("type_2")
    type3 = tmpGoodsObj.get("type_3")
            
    socket_id = request.socket_id
    ownerUID = tmpOwnerUser.getUID()
    targetUID = tmpTargetUser.getUID()
    
    log.print_warning(logger, "_use_props_bar exec, sockID:[%s], owner:[%s] to target:[%s] using props:[%s], goods_id[%s]" 
                      % (socket_id, ownerUID, targetUID, type3, tmpGoodsID))
       
    tmpBarManager = BarOrderManager.instance()      #酒吧名人堂管理对象    
    tmpSendMsgUtil = util.SendMsgUtil(request)      #消息发送器
    
    tmpSendMsgUtil.add_item("uid", ownerUID)        #使用者ID
    tmpSendMsgUtil.add_item("goods_id", tmpGoodsID) #道具ID
    tmpSendMsgUtil.add_item("type_3", type3)        #道具类别3
    
    room_id = tmpTargetUser.getRoomID(); #房间ID 
    tmpRoom = tmpBarManager.getRoomExt(cmd, tmpSendMsgUtil, socket_id, room_id)
    if tmpRoom is None:     #当前房间不存在， 则发错误消息
        return
    
    #----'深水炸弹'---判断是否能使用--
    tmpContiuneUID = 0  #继续聊天者ID(深水炸弹使用)
    if type3 in ['bomb']:  
        if not tmpRoom.isStatePK():#必须在约会PK场景中 
            tmpSendMsgUtil.update_res("use_props_need_pk")#道具需要在pk状态使用
            tmpSendMsgUtil.send(cmd)
            log.print_warning(logger, "_use_props_bar exec, socket_id:[%s], fail, type3 in ['bomb'] and not tmpRoom.isStatePK()" % socket_id)
            return
        
        usersDict = tmpRoom.getRoomUserObjMapExt()  #获取房间所有人信息,返回字典 '''    
        tmpUserOnly = usersDict["only"]             #裁判者 
        tmpUserOther = usersDict["other"]           #原配
        tmpUserPK = usersDict["pk"]                 #PK者
        #---目标使用者不能是自己和裁判
        if tmpTargetUser.getUID() in [tmpOwnerUser.getUID(), tmpUserOnly.getUID()]: 
            tmpStrErr = "targe_use_is_myself"
            if tmpTargetUser.getUID() in [tmpUserOnly.getUID()]: #目标是裁判
                tmpStrErr = "targe_use_is_only"
            tmpSendMsgUtil.update_res(tmpStrErr)#
            tmpSendMsgUtil.send(cmd)
            log.print_warning(logger, "_use_props_bar exec, socket_id:[%s], fail, type3 in ['bomb'] and tmpTargetUser.getUID() is myslef or onlyUser" % socket_id)
            return
        
        tmpContiuneUID = tmpUserOther.getUID()  #继续聊天者ID
        if tmpTargetUser.getUID() == tmpContiuneUID:
            tmpContiuneUID = tmpUserPK.getUID()
    
    #----防打扰牌--判断是否能使用---
    if type3 in ['nobother']:
        if tmpRoom.isStateNobother():   #房间当前是防打搅状态, 则不允许使用 
            tmpSendMsgUtil.update_res("useing_same_props")      #使用了同类道具
            tmpSendMsgUtil.send(cmd)
            return
        if tmpRoom.isStatePK():         #房间PK状态不能使用防打搅道具
            tmpSendMsgUtil.update_res("room_is_pk")
            tmpSendMsgUtil.send(cmd)
            return

    #背包类, 从"我的道具列表"减少一个, 并更新DB
    PropManager.instance().decreaseMyPropsAndUpdateToDB(tmpOwnerUser, type2, type3, tmpGoodsID)
            
        
    #--- "插入正在使用的道具列表", 更新DB, 构建道具回应消息
    tmpRecID = 0                                        #道具记录ID(酒吧类道具记录ID为0)
    tmpBeginTime = time.time()                          #道具购买时间
    tmpEndTime = tmpBeginTime + tmpGoodsObj.get('time') #道具相对购买时间是结束时间
    _create_props_msg(data, tmpOwnerUser, tmpTargetUser, type3, tmpGoodsID, tmpRecID, tmpBeginTime, tmpEndTime, tmpSendMsgUtil)
        
    #-----使用'深水炸弹'(深水炸弹&大棒&大便)把对方服装炸掉，并强制驱离约会现场'); 
    if type3 in ['bomb']:   
        if PropManager.instance().isUsingPropsCheeky(tmpTargetUser):   #---目标用户使用了"厚脸皮", 道具效果失败
            tmpSendMsgUtil.update_res("targe_use_props_cheeky")  
            tmpSendMsgUtil.send(cmd)
            log.print_warning(logger, "_use_props_bar exec, socket_id:[%s], fail, targeUser:[%s] use_props_cheeky" % (socket_id, tmpTargetUser.getUID()))
            return
        else:
            #-道具成功---给房间所有人发消息通知
            tmpRoom.sendMsgToAll(cmd, tmpSendMsgUtil)
            #---踢出对方    
            import process_bar_order
            process_bar_order._bar_send_pk_result(request, tmpRoom, tmpContiuneUID, killerName=tmpOwnerUser.getNickname()) 
            return
    
    #----给房间所有人发消息通知
    tmpRoom.sendMsgToAll(cmd, tmpSendMsgUtil)
    
    if type3 in ['nobother']:           #'防打扰牌'        #'酒吧类, 挂上防打扰牌，任何人不得插足、干扰'); 
        tmpRoom.setStateNobother(1)     #0: 默认, 1:使用了防打扰牌道具, 2:使用了隐形符
        tmpRoom.pushRoomUserBarState()  #给房间所有人push用户状态信息变化
        return
    elif type3 in ['specially']:      #'约会特效'        #'酒吧类, 绚烂的爱、气球广告、首页霓虹灯真爱宣言、小提琴伴奏、烛光晚餐'); 
        return
    elif type3 in ['magic']:          #'魔法卡片'        #'酒吧类, 把对方变成侏儒、猪头、鬼魂等变态形象， 魔咒时间自定');
        tmpTargetUser.setUserInfoPropMagic() #保存魔法卡片信息到个人信息里,提供其它人查询
        return
    
    
#---酒吧类道具处理--(现买现用)[取消使用, 因为酒吧类道具 改为先买, 后使用]
def _use_props_bar(cmd, request, data, tmpOwnerUser, tmpTargetUser, bUseToOther, tmpGoodsObj, tmpGoodsID, tmpRecID):
    tmpBarManager = BarOrderManager.instance()      #酒吧名人堂管理对象    
    tmpSendMsgUtil = util.SendMsgUtil(request)      #消息发送器
    
    type1 = tmpGoodsObj.get("type_1")
    type2 = tmpGoodsObj.get("type_2")
    type3 = tmpGoodsObj.get("type_3")
            
    socket_id = request.socket_id
    ownerUID = tmpOwnerUser.getUID()
    targetUID = tmpTargetUser.getUID()
    
    log.print_warning(logger, "_use_props_bar exec, sockID:[%s], owner:[%s] to target:[%s] using props:[%s], goods_id[%s]" 
                      % (socket_id, ownerUID, targetUID, type3, tmpGoodsID))
    
    tmpRoom = None
    room_id = tmpTargetUser.getRoomID(); #房间ID
    if type3 not in ['horn']: #----非大喇叭
        tmpRoom = tmpBarManager.getRoomExt(cmd, tmpSendMsgUtil, socket_id, room_id)
        if tmpRoom is None:     #当前房间不存在， 则发错误消息
            return
        
    tmpContiuneUID = 0  #继续聊天者ID(深水炸弹使用)
    if type3 in ['bomb']: #----'深水炸弹' 
        if not tmpRoom.isStatePK():#必须在约会PK场景中 
            tmpSendMsgUtil.update_res("use_props_need_pk")#道具需要在pk状态使用
            tmpSendMsgUtil.send(cmd)
            log.print_warning(logger, "_use_props_bar exec, socket_id:[%s], fail, type3 in ['bomb'] and not tmpRoom.isStatePK()" % socket_id)
            return
        
        usersDict = tmpRoom.getRoomUserObjMapExt()  #获取房间所有人信息,返回字典 '''    
        tmpUserOnly = usersDict["only"]             #裁判者 
        tmpUserOther = usersDict["other"]           #原配
        tmpUserPK = usersDict["pk"]                 #PK者
        #---目标使用者不能是自己和裁判
        if tmpTargetUser.getUID() in [tmpOwnerUser.getUID(), tmpUserOnly.getUID()]: 
            tmpStrErr = "targe_use_is_myself"
            if tmpTargetUser.getUID() in [tmpUserOnly.getUID()]: #目标是裁判
                tmpStrErr = "targe_use_is_only"
            tmpSendMsgUtil.update_res(tmpStrErr)#
            tmpSendMsgUtil.send(cmd)
            log.print_warning(logger, "_use_props_bar exec, socket_id:[%s], fail, type3 in ['bomb'] and tmpTargetUser.getUID() is myslef or onlyUser" % socket_id)
            return
        
        #---目标用户使用了"厚脸皮", 使用失败
        if PropManager.instance().isUsingPropsCheeky(tmpTargetUser):  
            tmpSendMsgUtil.update_res("targe_use_props_cheeky")  
            tmpSendMsgUtil.send(cmd)
            log.print_warning(logger, "_use_props_bar exec, socket_id:[%s], fail, targeUser:[%s] use_props_cheeky" % (socket_id, tmpTargetUser.getUID()))
            return
        
        tmpContiuneUID = tmpUserOther.getUID()  #继续聊天者ID
        if tmpTargetUser.getUID() == tmpContiuneUID:
            tmpContiuneUID = tmpUserPK.getUID()
        
        
    #----判断数值, 数值够, 则扣钱, 发送数值变化消息, 否则返回
    tmpGold = tmpGoodsObj.get('gold')
    tmpMoney = tmpGoodsObj.get('money')
            
    tmpLogicMapObj = ConfigManager.getLogicInfo("default_logic") #获取默认配置项        
    ConfigManager.setLogicInfoVal_Gold(tmpLogicMapObj, tmpGold, bNegative=True) #bNegative=True设置为负数
    ConfigManager.setLogicInfoVal_Money(tmpLogicMapObj, tmpMoney, bNegative=True)  
    if not util.CountUserUtil.judgeAndEditExt(cmd, request, tmpOwnerUser.getUID(), tmpLogicMapObj):
        return  #数值扣除不成功, 则返回
            
        
    #--- "插入正在使用的道具列表", 更新DB, 构建道具回应消息
    tmpRecID = 0                                        #道具记录ID(酒吧类道具记录ID为0)
    tmpBeginTime = time.time()                          #道具购买时间
    tmpEndTime = tmpBeginTime + tmpGoodsObj.get('time') #道具相对购买时间是结束时间
    _create_props_msg(data, tmpOwnerUser, tmpTargetUser, type3, tmpGoodsID, tmpRecID, tmpBeginTime, tmpEndTime, tmpSendMsgUtil)
            
    if type3 in ['horn']:#大喇叭, 所有人能看到我的发言或告白内容')    
        tmpMsg = tmpSendMsgUtil.getEncodeContent()  #消息编码
        UserManager.sendMsgToAll(cmd, msg=tmpMsg)   #给系统所有人发消息
        return
        
    #----给房间所有人发消息通知
    tmpRoom.sendMsgToAll(cmd, tmpSendMsgUtil)
    
    if type3 in ['bomb']:   #'深水炸弹'(深水炸弹&大棒&大便)把对方服装炸掉，并强制驱离约会现场');
        if not tmpRoom and tmpContiuneUID > 0:            
            import process_bar_order
            process_bar_order._bar_send_pk_result(request, tmpRoom, tmpContiuneUID, killerName=tmpOwnerUser.getNickname()) 
        return
    
    if type3 in ['nobother']:       #'防打扰牌'        #'酒吧类, 挂上防打扰牌，任何人不得插足、干扰'); 
        tmpRoom.setStateNobother(1)  #0: 默认, 1:使用了防打扰牌道具, 2:使用了隐形符
        return
    if type3 in ['specially']:      #'约会特效'        #'酒吧类, 绚烂的爱、气球广告、首页霓虹灯真爱宣言、小提琴伴奏、烛光晚餐'); 
        return
    if type3 in ['magic']:          #'魔法卡片'        #'酒吧类, 把对方变成侏儒、猪头、鬼魂等变态形象， 魔咒时间自定');
        tmpTargetUser.setUserInfoPropMagic() #保存魔法卡片信息到个人信息里,提供其它人查询
        return
    
        
#-----#使用道具---
def method_use_props(request, data):
    socket_id = request.socket_id
    log.print_debug(logger, "method_use_props exec, socket_id:[%s] data:%s" % (socket_id, data)) 
    cmd = "use_props"
    
    data_dict = json_decode(data)
    tmpTargetUID = data_dict.get('uid')     #对某人使用道具(目标用户)
    tmpGoodsID = data_dict.get('goods_id')  #道具商品ID
    tmpRecID = data_dict.get('rec_id')      #道具记录ID[当记录ID 为0, 则服务端使用"我的道具"中同样商品ID的道具]

    tmpBarManager = BarOrderManager.instance()      #酒吧名人堂管理对象    
    tmpSendMsgUtil = util.SendMsgUtil(request)      #消息发送器
    tmpOwnerUser = UserManager.getUserExt(cmd, tmpSendMsgUtil, socket_id);     
    if tmpOwnerUser is None:    #当前用户对象不存在， 则发错误消息
        return
    
    ownerUID = tmpOwnerUser.getUID()
    ownerNickname = tmpOwnerUser.getNickname()
    
    tmpTargetUser = tmpOwnerUser    #目标用户
    bUseToOther = False             #是否是对他人使用道具
    
    if tmpTargetUID in (0, ownerUID, None):
        tmpTargetUID = ownerUID
    else: #对其他人使用道具
        bUseToOther = True
        tmpTargetUser = UserManager.getUserByUIDExt(cmd, tmpSendMsgUtil, tmpTargetUID)
        if tmpTargetUser is None:   #目标用户不在线， 则发错误消息
            return
        if tmpOwnerUser.getSex()==tmpTargetUser.getSex():   
            #添加成功则执行任务
            task.taskManager.do_task(tmpOwnerUser,'day_task','magic_same_sex',tmpTargetUID)
    
    #从商场商品列表获取商品信息 ---
    tmpGoodsObj = store.getGoodsInfoExt(cmd, request, tmpGoodsID)
    if tmpGoodsObj is None: #商品ID不存在， 发错误消息， 退出
        return
    
    type1 = tmpGoodsObj.get("type_1")
    type2 = tmpGoodsObj.get("type_2")
    type3 = tmpGoodsObj.get("type_3")
    
    #---非道具或者装饰类道具, 返回错误码
    if type1 != "props" or type2 not in ("pack", "bar"):
        log.print_warning(logger, "method_use_props exec, socket_id:[%s] data:%s, fail, (type1:[%s] != 'props' or type2:[%s] not in ('pack', 'bar'))" 
                          % (socket_id, data, type1, type2)) 
        tmpSendMsgUtil.update_res("bad_request")
        tmpSendMsgUtil.send(cmd)
        return
    
    if type2 in ["pack"]:  #背包类道具
        _use_props_pack(cmd, request, data, tmpOwnerUser, tmpTargetUser, bUseToOther, tmpGoodsObj, tmpGoodsID, tmpRecID)
    else: #酒吧类道具
        #_use_props_bar(cmd, request, data, tmpOwnerUser, tmpTargetUser, bUseToOther, tmpGoodsObj, tmpGoodsID, tmpRecID)(现买现用)
        _use_props_bar_EXT(cmd, request, data, tmpOwnerUser, tmpTargetUser, bUseToOther, tmpGoodsObj, tmpGoodsID, tmpRecID)
    if type3 == 'wine':
        task.taskManager.do_task(tmpOwnerUser,'first','first_drink_wine',tmpTargetUID)
  
        

#-----#查询某人正在使用的道具---
def method_query_using_props(request, data):
    socket_id = request.socket_id
    log.print_debug(logger, "method_query_using_props exec, socket_id:[%s] data:%s" % (socket_id, data)) 
    cmd = "query_using_props"
    
    data_dict = json_decode(data)
    tmpTargetUID = data_dict.get('uid')     #对某人使用道具(目标用户)

    tmpSendMsgUtil = util.SendMsgUtil(request)      #消息发送器
    tmpOwnerUser = UserManager.getUserExt(cmd, tmpSendMsgUtil, socket_id);     
    if tmpOwnerUser is None:    #当前用户对象不存在， 则发错误消息
        return
    
    bUseToOther = False     #是否是对他人使用道具
    ownerUID = tmpOwnerUser.getUID()
    tmpTargetUser = tmpOwnerUser
    if tmpTargetUID != 0 and tmpTargetUID != ownerUID: #对其他人使用道具
        bUseToOther = True
        tmpTargetUser = UserManager.getUserByUIDExt(cmd, tmpSendMsgUtil, tmpTargetUID)
        if tmpTargetUser is None:   #目标用户不在线， 则发错误消息
            return
    
    tmpInfoList = []
    for k, v in tmpTargetUser.getMyUsingProps():#获取正在使用的道具信息
        tmpInfoList.append(v)
    tmpSendMsgUtil.add_item("info", tmpInfoList)
    
    #发送消息---
    tmpSendMsgUtil.send(cmd)
        


#------------------------------------------
#----方法注册---------
util.registMethod("use_props", method_use_props)                    #使用道具
util.registMethod("query_using_props", method_query_using_props)    #查询某人正在使用的道具

